<template>
  <!-- 账单详情 -->
  <div
    class="CheckDetail"
    v-if="info"
  >
    <div class="g-con">
      <el-form
        ref="formEl"
        :model="formData"
        :rules="rules"
        label-width="120px"
        status-icon
        label-position="left"
        label-suffix="："
      >
        <div class="header flexsb">
          <div class="flexsc nowrap">
            <!-- <div>帐单编号：</div>
            <div></div> -->
            <div class="flexsc mr-2">{{ t('dockRepair.label3') }}: {{ getDictLabel('currency', info.dockShowInfoVo.quoteOrderCurrency) }}</div>
            <div class="flexsc">{{ t('dockRepair.label4') }}: {{ getDictLabel('currency', info.dockShowInfoVo.payCurrency) }}</div>
          </div>
          <div
            class="flexec"
            v-if="type === 'add'"
          >
            <el-button
              type="primary"
              @click="handleSave"
            >
              {{ t('save') }}
            </el-button>
            <el-button
              type="primary"
              @click="handleSynchronization"
            >
              {{ t('userCenter.b1') }}
            </el-button>
            <!-- <el-button @click="exportFn">
              {{ t('export') }}
            </el-button> -->
          </div>
          <div
            class="flexec"
            v-if="type === 'detail'"
          >
            <!-- <el-button @click="exportFn">
              {{ t('export') }}
            </el-button> -->
          </div>
        </div>

        <div class="info sm mt-3">
          <div class="tit">
            {{ t('DockOrderOnlineQuotation.t9') }}
          </div>
          <div class="con mt-2">
            <div class="item">
              <div class="label">{{ t('DockOrderOnlineQuotation.sm_l1') }}:</div>
              <div class="value">
                {{ info.dockQuotationVo.statementRepairPeriod }}
              </div>
            </div>
            <div class="item mt-2">
              <div class="label">{{ t('DockOrderOnlineQuotation.sm_l2') }}:</div>
              <div class="value">
                {{ info.dockQuotationVo.statementPrice }}
              </div>
            </div>
            <div class="item mt-2">
              <div class="label">{{ t('DockOrderOnlineQuotation.sm_l3') }}:</div>
              <div
                class="value"
                style="white-space: pre"
              >
                {{ info.dockQuotationVo.statementPayment }}
              </div>
            </div>
            <div class="item mt-2">
              <div class="label">{{ t('DockOrderOnlineQuotation.sm_l4') }}:</div>
              <div class="value">
                {{ info.dockQuotationVo.statementDelayPenalty }}
              </div>
            </div>
            <div class="item mt-2">
              <div class="label">{{ t('DockOrderOnlineQuotation.sm_l5') }}:</div>
              <div class="value">
                {{ info.dockQuotationVo.statementValidity }}
              </div>
            </div>
            <div
              class="item mt-2"
              v-if="info.dockShowInfoVo.quoteOrderCurrency === 'currency_1'"
            >
              <div class="label">{{ t('DockOrderOnlineQuotation.t17') }}:</div>
              <div class="value">{{ info.dockQuotationVo.rate }}%</div>
            </div>
            <div class="item mt-2">
              <div class="label">{{ t('DockOrderOnlineQuotation.t48') }}:</div>
              <div
                class="value"
                style="white-space: pre"
              >
                {{ info.dockQuotationVo.quoteDescription }}
              </div>
            </div>
          </div>
        </div>

        <!-- <div class="info mt-3">
          <div class="tit">{{ t('DockOrderOnlineQuotation.t21') }}</div>
          <div class="con mt-2">
            <el-table
              :data="info.quotationImportList"
              style="width: 100%"
            >
              <el-table-column
                :label="t('DockOrderOnlineQuotation.t22')"
                align="center"
                prop="importanceType"
              >
              </el-table-column>
              <el-table-column
                :label="t('DockOrderOnlineQuotation.t23')"
                align="center"
                prop="unit"
              >
              </el-table-column>
              <el-table-column
                label="单价"
                align="center"
                prop="importancePrice"
              >
                <template
                  #default="scope"
                  v-if="type === 'add'"
                >
                  <el-input-number
                    :controls="false"
                    :min="0"
                    v-model="scope.row.importancePrice"
                  />
                </template>
              </el-table-column>
              <el-table-column
                :label="t('DockOrderOnlineQuotation.t25')"
                align="center"
                prop="projectContent"
              >
                <template
                  #default="scope"
                  v-if="type === 'add'"
                >
                  <el-input v-model="scope.row.projectContent" />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div> -->
      </el-form>

      <div class="flexsb mt-3">
        <div class="wp-50">{{ t('DockOrderOnlineQuotation.t27') }}: {{ info.dockShowInfoVo.orderNo }}</div>
        <div class="wp-50">{{ t('DockOrderOnlineQuotation.t28') }}: {{ info.dockShowInfoVo.dockOrderName }}</div>
      </div>

      <div class="info mt-3">
        <!-- 人员信息 -->
        <div class="tit">{{ t('DockOrderOnlineQuotation.t29') }}</div>
        <div class="con flexsb mt-2">
          <div>{{ t('DockOrderOnlineQuotation.t30') }}: {{ info.dockShowInfoVo.createByName }}</div>
          <div>{{ t('DockOrderOnlineQuotation.t31') }}: {{ dateFormat(info.dockShowInfoVo.createTime) }}</div>
          <div>{{ t('DockOrderOnlineQuotation.t32') }}: {{ dateFormat(info.dockShowInfoVo.updateTime) }}</div>
          <div>{{ t('DockOrderOnlineQuotation.t33') }}: {{ dateFormat(info.dockShowInfoVo.quotationEndTime) }}</div>
        </div>
      </div>

      <div
        class="info ship mt-2"
        v-if="info.shcwShippingVo"
      >
        <div class="left">
          <img
            :src="info.shcwShippingVo.picture"
            alt=""
          />
        </div>
        <div class="right">
          <div class="title flexsc">
            <div class="a mr-2">{{ info.shcwShippingVo.shippingName }}</div>
            <div class="b flexcc">{{ t(`dockRepair.IMOnumber`) }}:{{ info.shcwShippingVo.shippingNo }}</div>
          </div>
          <div class="attr mt-2">
            <div class="item">
              <span>{{ t(`dockRepair.attr1`) }}:</span>
              <span>{{ getDictLabel('ships_type', info.shcwShippingVo.shippingType) }}</span>
            </div>
            <div class="item">
              <span>{{ t(`dockRepair.attr2`) }}:</span>
              <span>{{ info.shcwShippingVo.totalLength }}</span>
            </div>
            <div class="item">
              <span>{{ t(`dockRepair.attr3`) }}:</span>
              <span>{{ info.shcwShippingVo.yearOfConstruction }}</span>
            </div>
            <div class="item">
              <span>{{ t(`dockRepair.attr4`) }}:</span>
              <span>{{ info.shcwShippingVo.nationality }}</span>
            </div>
            <div class="item">
              <span>{{ t(`dockRepair.attr5`) }}:</span>
              <span>{{ getDictLabel('classification_society', info.shcwShippingVo.classificationSociety) }}</span>
            </div>
            <div class="item">
              <span>{{ t(`dockRepair.attr6`) }}:</span>
              <span>{{ info.shcwShippingVo.portRegistry }}</span>
            </div>
            <div class="item">
              <span>{{ t(`dockRepair.attr7`) }}:</span>
              <span>{{ info.shcwShippingVo.shipowner }}</span>
            </div>
            <div class="item">
              <span>{{ t(`dockRepair.attr8`) }}:</span>
              <span>{{ info.shcwShippingVo.shipManagement }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="info mt-3">
        <div class="tit">
          {{ t('DockOrderOnlineQuotation.t34') }}
        </div>
        <div class="con mt-2">
          {{ info.dockShowInfoVo.remark }}
        </div>
      </div>

      <div class="info mt-3 keyword">
        <div class="tit">
          {{ t('DockOrderOnlineQuotation.t35') }}
        </div>
        <div class="con mt-2">
          <!-- <el-table :data="info.dockShowInfoVo.dockImportProjectBoList">
            <el-table-column
              prop="projectName"
              :label="t('DockOrderOnlineQuotation.t36')"
            />
            <el-table-column
              prop="projectContent"
              :label="t('DockOrderOnlineQuotation.t37')"
            />
            <el-table-column
              prop="makeCount"
              :label="t('DockOrderOnlineQuotation.t38')"
            />
          </el-table> -->
          <div
            :class="['item', 'flexcc']"
            v-for="item in info.dockShowInfoVo.dockImportProjectBoList"
            :key="item.projectId"
          >
            {{ item.projectName }}
          </div>
        </div>
      </div>

      <div class="info mt-3">
        <div class="table">
          <el-auto-resizer>
            <template #default="{ height, width }">
              <el-table-v2
                :columns="columns"
                :data="tableData"
                :width="width"
                :height="height"
                fixed
              />
            </template>
          </el-auto-resizer>
        </div>
      </div>

      <div class="info mt-3">
        <div class="tit">{{ t('attachments') }}</div>
        <div class="con mt-2">
          <div
            v-for="(item, index) in info.urlList"
            :key="index"
          >
            <a
              :href="item.url"
              target="_blank"
            >
              {{ item.file_name }}
            </a>
          </div>
        </div>
      </div>
    </div>

    <!-- 确认框 -->
    <Confirm
      v-if="synchronizationVisible"
      :visible="synchronizationVisible"
      :text="t('userCenter.synchronizationText')"
      @close="synchronizationVisible = false"
      @cancel="synchronizationVisible = false"
      @confirm="synchronizationConfirm"
    />
  </div>
</template>

<script setup lang="jsx">
import { ref, reactive, onBeforeMount, watch, unref, computed, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { getFinishOrderDetailApi, quotoImportancePriceListApi, saveFinishOrderApi, updateShcwFinishOrderDetailApi, exportFinishOrderApi, synchronizedDemandSideApi } from '@/service/dockOrder'
import { dateFormat, setItemNumber, download, amountFormat } from '@/utils/index'
import Confirm from '@/components/Confirm.vue'

import useDict from '@/hooks/useDict'
const { dictData, getDictData, getDictLabel } = useDict()

onBeforeMount(() => {
  init()
})

const { t, locale } = useI18n()
watch(locale, () => {
  init()
})

const router = useRouter()
const route = useRoute()

const id = route.query.id
const type = ref('add')

// 保存
const handleSave = () => {
  const params = {
    id,
    quotationImportList: info.value.quotationImportList
  }
  saveFinishOrderApi(params).then(({ msg }) => {
    ElMessage.success(msg)
    getDetail()
  })
}

// 同步给需求方
const synchronizationVisible = ref(false)
const handleSynchronization = () => {
  synchronizationVisible.value = true
}
const synchronizationConfirm = () => {
  synchronizedDemandSideApi({
    finishId: id
  }).then(({ msg }) => {
    ElMessage.success(msg)
    synchronizationVisible.value = false
    getDetail()
  })
}

// 表单
const formEl = ref(null)
const formData = ref({})
const rules = ref({})

// 查询报价重要单价列表
const optionsImportancePrice = ref([])
const getQuotoImportancePrice = () => {
  quotoImportancePriceListApi().then(({ data }) => {
    optionsImportancePrice.value = data
  })
}

// 报价单详情
const info = ref(null)
const getDetail = async () => {
  await getFinishOrderDetailApi(id).then(({ data }) => {
    info.value = data

    const { finishOrderDetailList, finishStatus } = data

    // finishStatus 0未完成 1已完成
    const obj = {
      0: 'add',
      1: 'detail'
    }
    type.value = obj[finishStatus]

    if (finishOrderDetailList) {
      finishOrderDetailList.forEach((item) => {
        item.isSave = true
      })
      tableData.value = finishOrderDetailList
      setItemNumber(finishOrderDetailList)
    }
  })
}

// 表格 列
const columns = ref([])
const tableData = ref([])

const getColumns = () => {
  columns.value = [
    {
      title: t('dockRepair.coltit1'), // 项目编号
      key: 'itemNumber',
      dataKey: 'itemNumber',
      width: 150
    },
    {
      title: t('dockRepair.coltit2'), // 项目类型
      key: 'projectName',
      dataKey: 'projectName',
      width: 450,
      cellRenderer: ({ rowData, rowIndex }) => {
        let projectContent = ''
        if (['4'].includes(rowData.dataType)) {
          const { projectContent1, projectContent2, projectContent3, projectContent4 } = JSON.parse(rowData.projectContent)
          projectContent = `${t('userCenter.projectContent1')}${projectContent1}mm,${t('userCenter.projectContent2')}${projectContent2}mm,${t('userCenter.projectContent3')}${projectContent3}mm,${t('userCenter.projectContent4')}${projectContent4}`
        } else projectContent = rowData.projectContent
        return `${rowData.projectName}${projectContent || ''}`
      }
    },
    // {
    //   title: t('dockRepair.coltit3'), // 项目类型说明
    //   key: 'projectContent',
    //   dataKey: 'projectContent',
    //   width: 150,
    //   cellRenderer: ({ rowData, rowIndex }) => {
    //     if (['4'].includes(rowData.dataType)) {
    //       const { projectContent1, projectContent2, projectContent3, projectContent4 } = JSON.parse(rowData.projectContent)
    //       return `${t('userCenter.projectContent1')}${projectContent1}mm,${t('userCenter.projectContent2')}${projectContent2}mm,${t('userCenter.projectContent3')}${projectContent3}mm,${t('userCenter.projectContent4')}${projectContent4}`
    //     }
    //     return rowData.projectContent
    //   }
    // },
    {
      title: t('dockRepair.coltit4'), // 单位
      key: 'unit',
      dataKey: 'unit',
      width: 130
    },
    {
      title: t('dockRepair.coltit5'), // 数量
      key: 'requireCount',
      dataKey: 'requireCount',
      width: 130
    },
    {
      title: t('userCenter.price'), //
      key: 'price',
      dataKey: 'price',
      width: 130,
      cellRenderer: ({ rowData, rowIndex }) => {
        if (rowData.isSave) {
          return amountFormat(rowData.price)
        }
        return (
          <>
            <el-input-number
              v-model={rowData.price}
              controls={false}
              min={0}
            />
          </>
        )
      }
    },
    {
      title: t('userCenter.discount'), //
      key: 'discount',
      dataKey: 'discount',
      width: 130,
      cellRenderer: ({ rowData, rowIndex }) => {
        if (rowData.isSave) {
          return rowData.discount !== null ? `${rowData.discount}%` :''
        }
        return (
          <>
            <el-input-number
              v-model={rowData.discount}
              controls={false}
              min={0}
            />
          </>
        )
      }
    },
    {
      title: t('userCenter.amount'), //
      key: 'amount',
      dataKey: 'amount',
      width: 130,
      cellRenderer: ({ rowData, rowIndex }) => {
        if (rowData.isSave) {
          return amountFormat(rowData.amount)
        }
        return (
          <>
            <el-input-number
              v-model={rowData.amount}
              controls={false}
              min={0}
            />
          </>
        )
      }
    },
    {
      title: t('userCenter.remark'), //
      key: 'remark',
      dataKey: 'remark',
      width: 200,
      cellRenderer: ({ rowData, rowIndex }) => {
        return rowData.remark
      }
    }
  ]

  if (type.value === 'add') {
    columns.value.push({
      title: t('dockRepair.coltit6'), // 操作
      width: 100,
      fixed: 'right',
      cellRenderer: ({ rowData, rowIndex }) => {
        if ([0, 1].includes(rowData.projectLevel)) {
          return
        }

        // 保存
        const handleRowSave = () => {
          updateShcwFinishOrderDetailApi({ finishOrderId: id, ...rowData }).then(({ msg }) => {
            ElMessage.success(msg)
            rowData.isSave = true
          })
        }

        // 编辑
        const handleRowEdit = (value) => {
          rowData.isSave = false
        }

        return (
          <>
            {rowData.isSave ? (
              <img
                src={new URL('@/assets/img/icon_bianji.png', import.meta.url)}
                height="22"
                class="mr-2"
                onClick={handleRowEdit}
              />
            ) : (
              <img
                src={new URL('@/assets/img/icon_baocun.png', import.meta.url)}
                height="22"
                class="mr-2"
                onClick={handleRowSave}
              />
            )}
          </>
        )
      }
    })
  }
}

// 导出
const exportFn = () => {
  exportFinishOrderApi({ id }).then((res) => {
    download(res)
  })
}

//
const init = async () => {
  getDictData('currency')
  getDictData('ships_type')
  getDictData('classification_society')
  getQuotoImportancePrice()
  await getDetail()
  getColumns()
}
</script>

<style scoped lang="scss">
.CheckDetail {
  background: #f5f5f5;
  padding: 30px 0;
  margin-bottom: -76px;

  .el-button {
    min-width: 140px;
  }
  .addbtn {
    color: var(--mainColor);
    cursor: pointer;
  }

  .checkPassword {
    padding: 100px 400px;
  }

  .header {
  }

  .keyword .con {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
    .item {
      cursor: default;
      color: #606266;
      border: 1px solid #dcdfe6;
      padding: 5px;
      border-radius: 4px;
    }
  }

  .info {
    background: #fff;
    padding: 24px;
    > .tit {
      border-bottom: 2px solid #252628;
      font-weight: bold;
      padding: 10px 0;
    }

    &.sm {
      .con {
        .item {
          display: grid;
          grid-template-columns: 100px auto;
          gap: 10px;
        }
      }
    }
  }
  .ship {
    display: grid;
    grid-template-columns: 272px auto;
    gap: 30px;
    .left {
      width: 272px;
      height: 180px;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    .right {
      .title {
        .a {
          font-size: 20px;
          font-weight: bold;
        }
        .b {
          min-width: 180px;
          padding: 0 10px;
          height: 38px;
          background: rgba($color: #3376e5, $alpha: 0.1);
          color: #3376e5;
          border-radius: 4px;
        }
      }
      .attr {
        display: grid;
        grid-template-columns: repeat(2, 50%);
        gap: 15px;
        span {
          font-size: 12px;
          &:first-of-type {
            color: #9d9fa5;
            margin-right: 5px;
          }
        }
      }
    }
  }

  .table {
    border-top: 2px solid #252628;
    height: 700px;

    :deep(.el-table-v2__header-cell) {
      background: #f0f3f8;
      color: #252628;
    }
    :deep(.no-save) {
      background: #f9ecd9;
    }
  }

  :deep(.el-input-number .el-input__inner) {
    text-align: left;
  }
}
</style>
